
#include "Console.h"
#include "Graphics/Font.h"

#include <GL/gl.h>
#include <list>

Console::Console(Vector2D bottom_left, Vector2D top_right) :
    font("data/font3.png", 0.013f, 0.01f),
    bottom_left(bottom_left),
    top_right(top_right),
    max_lines(5) {

    row_height = (top_right.y - bottom_left.y)/(float)max_lines;
}

Console::~Console(){

}

void Console::addEntry(std::string text){
    // TODO: break it up over multiple lines if too long
    text_buffer.push_back(text);
    while(text_buffer.size() > max_lines){
        text_buffer.pop_front();
    }
}

void Console::render(void){
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    renderConsoleBackground();
    renderConsoleText();

    glDisable(GL_BLEND);
}

void Console::clear(void){
    text_buffer.clear();
}

void Console::renderConsoleBackground(void){
    glPushMatrix();

    glColor4f(0.0f, 0.0f, 0.0f, 0.5f);
    glBegin(GL_QUADS);
      glVertex3f(bottom_left.x, bottom_left.y, 0.0f);
      glVertex3f(bottom_left.x, top_right.y,   0.0f);
      glVertex3f(top_right.x,   top_right.y,   0.0f);
      glVertex3f(top_right.x,   bottom_left.y, 0.0f);
    glEnd();

    glDisable(GL_BLEND);
    glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
    glBegin(GL_LINE_STRIP);
      glVertex3f(bottom_left.x, bottom_left.y, 0.0f);
      glVertex3f(bottom_left.x, top_right.y,   0.0f);
      glVertex3f(top_right.x,   top_right.y,   0.0f);
      glVertex3f(top_right.x,   bottom_left.y, 0.0f);
      glVertex3f(bottom_left.x, bottom_left.y, 0.0f);
    glEnd();

    glPopMatrix();
}

void Console::renderConsoleText(void){
    std::list<std::string>::iterator it = text_buffer.begin();
    unsigned i = 0;   

    while(it != text_buffer.end()){

        glPushMatrix();
        glTranslatef(bottom_left.x+0.015f, bottom_left.y + (i+1)*row_height, 0.0f);
        glColor4f(1.0f, 0.5f, 0.5f, 1.0f);
        font.renderString(*it);
        glPopMatrix();

        ++it;
        ++i;
    } 
}

